package com.hfy.pcberpbackend.controller;

import com.hfy.pcberpbackend.entity.Customer;
import com.hfy.pcberpbackend.service.CustomerService;
import com.hfy.pcberpbackend.dto.CustomerQueryDTO;
import com.hfy.pcberpbackend.dto.BatchDeleteDTO;
import com.hfy.pcberpbackend.common.Result;
import com.hfy.pcberpbackend.common.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

/**
 * 客户Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/customers")
@RequiredArgsConstructor
@Validated
public class CustomerController {
    
    private final CustomerService customerService;
    
    /**
     * 获取客户列表
     */
    @GetMapping
    public Result<PageResult<Customer>> getCustomerList(CustomerQueryDTO query) {
        log.info("获取客户列表，查询条件：{}", query);
        
        try {
            PageResult<Customer> result = customerService.getCustomerPage(query);
            return Result.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取客户列表失败", e);
            return Result.error("获取客户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取客户详情
     */
    @GetMapping("/{id}")
    public Result<Customer> getCustomerById(@PathVariable Long id) {
        log.info("根据ID获取客户详情，ID：{}", id);
        
        try {
            Customer customer = customerService.getCustomerById(id);
            return Result.success("获取成功", customer);
        } catch (RuntimeException e) {
            log.error("获取客户详情失败", e);
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            log.error("获取客户详情失败", e);
            return Result.error("获取客户详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增客户
     */
    @PostMapping
    public Result<Map<String, Long>> createCustomer(@Valid @RequestBody Customer customer) {
        log.info("新增客户：{}", customer);
        
        try {
            Long id = customerService.createCustomer(customer);
            Map<String, Long> result = new HashMap<>();
            result.put("id", id);
            return Result.success("新增成功", result);
        } catch (RuntimeException e) {
            log.error("新增客户失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("新增客户失败", e);
            return Result.error("新增客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户信息
     */
    @PutMapping("/{id}")
    public Result<Void> updateCustomer(@PathVariable Long id, @Valid @RequestBody Customer customer) {
        log.info("更新客户信息，ID：{}，数据：{}", id, customer);
        
        try {
            customerService.updateCustomer(id, customer);
            return Result.success("更新成功");
        } catch (RuntimeException e) {
            log.error("更新客户失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("更新客户失败", e);
            return Result.error("更新客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除客户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteCustomer(@PathVariable Long id) {
        log.info("删除客户，ID：{}", id);
        
        try {
            customerService.deleteCustomer(id);
            return Result.success("删除成功");
        } catch (RuntimeException e) {
            log.error("删除客户失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("删除客户失败", e);
            return Result.error("删除客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除客户
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteCustomers(@Valid @RequestBody BatchDeleteDTO batchDeleteDTO) {
        log.info("批量删除客户，IDs：{}", batchDeleteDTO.getIds());
        
        try {
            customerService.batchDeleteCustomers(batchDeleteDTO.getIds());
            return Result.success("批量删除成功");
        } catch (RuntimeException e) {
            log.error("批量删除客户失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("批量删除客户失败", e);
            return Result.error("批量删除客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出客户Excel
     */
    @GetMapping("/export")
    public Result<String> exportCustomers(CustomerQueryDTO query) {
        log.info("导出客户Excel，查询条件：{}", query);
        
        try {
            // TODO: 实现Excel导出功能
            return Result.success("导出功能开发中");
        } catch (Exception e) {
            log.error("导出客户Excel失败", e);
            return Result.error("导出客户Excel失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查客户代码唯一性
     */
    @GetMapping("/check-code")
    public Result<Map<String, Boolean>> checkCustomerCode(
            @RequestParam String customerCode,
            @RequestParam(required = false) Long excludeId) {
        log.info("检查客户代码唯一性，代码：{}，排除ID：{}", customerCode, excludeId);
        
        try {
            boolean exists = customerService.isCustomerCodeExists(customerCode, excludeId);
            Map<String, Boolean> result = new HashMap<>();
            result.put("exists", exists);
            return Result.success("检查完成", result);
        } catch (Exception e) {
            log.error("检查客户代码唯一性失败", e);
            return Result.error("检查客户代码唯一性失败：" + e.getMessage());
        }
    }
    
    /**
     * 模糊搜索客户
     * 支持按客户代码、客户名称、公司名称进行模糊查询
     */
    @GetMapping("/search")
    public Result<List<Customer>> searchCustomers(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "20") Integer size) {
        log.info("模糊搜索客户，关键词：{}，数量限制：{}", keyword, size);
        
        try {
            List<Customer> customers = customerService.searchCustomers(keyword, size);
            return Result.success("搜索成功", customers);
        } catch (Exception e) {
            log.error("模糊搜索客户失败", e);
            return Result.error("模糊搜索客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据客户代码获取客户详情
     */
    @GetMapping("/code/{customerCode}")
    public Result<Customer> getCustomerByCode(@PathVariable String customerCode) {
        log.info("根据客户代码获取客户详情，客户代码：{}", customerCode);
        
        try {
            Customer customer = customerService.getCustomerByCode(customerCode);
            return Result.success("获取成功", customer);
        } catch (RuntimeException e) {
            log.error("获取客户详情失败", e);
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            log.error("获取客户详情失败", e);
            return Result.error("获取客户详情失败：" + e.getMessage());
        }
    }
} 